require("dotenv").config();
const mysql = require("mysql2/promise");

console.log("环境变量加载状态:", process.env.DB_USER, process.env.DB_PASSWORD);

async function setupDatabase() {
  let connection;

  try {
    // 创建数据库连接
    connection = await mysql.createConnection({
      socketPath: "/tmp/mysql.sock",
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
    });

    // 创建数据库
    await connection.query(
      `CREATE DATABASE IF NOT EXISTS ${process.env.DB_NAME}`
    );
    console.log(`数据库 ${process.env.DB_NAME} 创建成功或已存在`);

    // 使用创建的数据库
    await connection.query(`USE ${process.env.DB_NAME}`);

    // 创建用户表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) NOT NULL UNIQUE,
        password VARCHAR(255) NOT NULL,
        wallet_address VARCHAR(255),
        balance DECIMAL(18, 8) DEFAULT 0,
        current_chain VARCHAR(50) DEFAULT 'ethereum',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);
    console.log("用户表创建成功");

    // 创建交易记录表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS transactions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        transaction_type ENUM('deposit', 'withdrawal', 'mint_nft', 'transfer') NOT NULL,
        amount DECIMAL(18, 8),
        token_type VARCHAR(50),
        token_address VARCHAR(255),
        token_id VARCHAR(255),
        transaction_hash VARCHAR(255),
        status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
      )
    `);
    console.log("交易记录表创建成功");

    // 创建资产表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS assets (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        asset_type ENUM('token', 'nft') NOT NULL,
        token_symbol VARCHAR(50),
        token_address VARCHAR(255),
        token_id VARCHAR(255),
        balance DECIMAL(18, 8) DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id)
      )
    `);
    console.log("资产表创建成功");

    console.log("数据库设置完成");
  } catch (error) {
    console.error("设置数据库时出错:", error);
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

// 执行设置
setupDatabase();
